#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/25 14:47
# @Author : cjw
from typing import List

from fastapi import APIRouter, Body, Depends, HTTPException, status, BackgroundTasks
from fastapi.encoders import jsonable_encoder
from pydantic.networks import EmailStr
from sqlalchemy.orm import Session

from app import crud
from app.api.utils.db import get_db
from app.api.utils.security import get_current_active_superuser
from app.core.config import settings
from app.models.user import User as DBUser
from app.schemas.user import User, UserCreate, UserUpdate
from app.utils.mail import send_new_account_email

router = APIRouter()


@router.get('/', response_model=List[User], summary='获取多个用户')
def read_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    """
    获取多个用户，默认返回10个用户
    - **skip**: 起始位置
    - **limit**: 获取的数量
    """
    return crud.user.get_multi(db, skip=skip, limit=limit)


@router.post('/', response_model=User, summary='创建用户')
def create_user(user_in: UserCreate, bts: BackgroundTasks, db: Session = Depends(get_db)):
    """创建用户"""
    user = crud.user.get_by_email(db, email=user_in.email)
    if user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='用户邮箱已存在'
        )
    user = crud.user.create(db, obj_in=user_in)
    if settings.EMAILS_ENABLED and user_in.email:
        bts.add_task(send_new_account_email, settings.EMAIL_TEST_USER, user_in.email, user_in.password)
    return user
